(function() {

	var app = angular.module('babyApp', [ 'ngResource' ]);

	app.config(function($httpProvider) {
		// Enable cross domain calls
		$httpProvider.defaults.useXDomain = true;

		// Remove the header used to identify ajax call that would prevent CORS from working
		delete $httpProvider.defaults.headers.common['X-Requested-With'];
	});

	app.factory("LogFactory", function($resource) {
		
// var url = 'http://default-environment-2xgz38vab8.elasticbeanstalk.com/log/get/:id';
		var url = 'http://localhost\\:5555/logdata/:id';
		
		return $resource(url, {}, {
			'get' : {
				method : 'GET',
				headers : {
					'Access-Control-Allow-Origin' : '*'
				}
			},
			'post' : {
				method : 'POST',
				isArray: false,
                headers: { 
                	'Access-Control-Allow-Origin' : '*',
                	'Content-Type' : 'application/json, */*; charset=UTF-8'
                }
			},
			'query' : {
				method : 'GET',
				headers : {
					'Access-Control-Allow-Origin' : '*'
				},
				isArray : true
			},
			'remove' : {
				method : 'DELETE',
				headers : {
					'Access-Control-Allow-Origin' : '*'
				}
			},
			'delete' : {
				method : 'DELETE',
				headers : {
					'Access-Control-Allow-Origin' : '*'
				}
			},
			'querySinceSunday' : {
				url : "http://localhost\\:5555/logdata/sinceSunday",
				method : 'GET',
				headers : {
					'Access-Control-Allow-Origin' : '*'
				},
				isArray : true
			},
			'querySinceThe1st' : {
				url : "http://localhost\\:5555/logdata/since1st",
				method : 'GET',
				headers : {
					'Access-Control-Allow-Origin' : '*'
				},
				isArray : true
			},
			'querySinceLastNDays' : {
				url : "http://localhost\\:5555/logdata/lastNdays/:days",
				method : 'GET',
				headers : {
					'Access-Control-Allow-Origin' : '*'
				},
				isArray : true
			},
			'queryForTheMonthOf' : {
				url : "http://localhost\\:5555/logdata/forTheMonthOf",
				method : 'POST',
				headers : { 
                	'Access-Control-Allow-Origin' : '*',
                },
				isArray : true
			},
			'queryLogMonths' : {
				url : "http://localhost\\:5555/logdata/months",
				method : 'GET',
				headers : {
					'Access-Control-Allow-Origin' : '*'
				},
				isArray : true
			},
			
		});
	});

	app.controller("LogController", [ '$scope', '$filter', '$log', 'dateFilter', 'LogFactory', function($scope, $filter, $log, dateFilter, LogFactory) {

		$scope.logs = [];
		$scope.logMonths = [];
		
		// /////////////////////////////////////////////
		$scope.findAll = function() {
			$log.log('Querying for all logs');
			LogFactory.query(function(data) {
				$scope.logs = data;
				$scope.search();
			});
		}

		$scope.findSinceSunday = function() {
			$log.log('Querying for all logs since last Sunday');
			LogFactory.querySinceSunday(function(data) {
				$scope.logs = data;
				$scope.search();
			});
		}

		$scope.findSinceThe1st = function() {
			$log.log('Querying for all logs since the 1st');
			LogFactory.querySinceThe1st(function(data) {
				$scope.logs = data;
				$scope.search();
			});
		}

		$scope.findSinceLastNDays = function(days) {
			$log.log('Querying for all logs since last ' + days + ' days');
			LogFactory.querySinceLastNDays({ days : days }, function(data) {
				$scope.logs = data;
				$scope.search();
			});
		}

		$scope.findAllForTheMonthOf = function(month) {
			$log.log('Querying for all logs for the month of ' + month);
			LogFactory.queryForTheMonthOf({ month : month }, function(data) {
				$scope.logs = data;
				$scope.search();
			});
		}

		$scope.findOne = function(id) {
			$log.log('Fetching log[' + id + ']');
			LogFactory.get({ id : 1 }, function(data) {
				$scope.logs = [];
				$scope.logs[0] = data;
				$scope.search();
			});
		}

		$scope.save = function(log) {
			$log.log('Saving log: [' + log + ']');
			LogFactory.post(log);
			$scope.findSinceThe1st();
		}

		$scope.delete = function(id) {
			$log.log('Deleting log[' + id + ']');
			LogFactory.delete({ id : id }, {'dummy post data':'dummy post value'}, function(data) {
				$log.info('Delete succeeded');
				$scope.findSinceThe1st();
			}, function(data) {
				$log.error('Delete did not succeed');
			});
			
		}

		$scope.findLogMonths = function() {
			$log.log('Querying for log months');
			LogFactory.queryLogMonths(function(data) {
				 $scope.logMonths = data;
			});
		}


		$scope.findSinceThe1st();
		$scope.findLogMonths();

		var now = new Date();
		$scope.newLog = {
			"timestamp" : now,
			"leftBreast" : 15,
			"rightBreast" : 20,
			"pumped" : 30,
			"formula" : 30,
			"diaper" : "WD",
			"updateUser" : "Amruta [ng]",
			"updateTimestamp" : now
		};

		// /////////////////////////////////////////////

		$scope.newLog.timestamp = new Date();
		$scope.timestampString = dateFilter($scope.newLog.timestamp, "MM-dd-yyyy");

		$scope.$watch('newLog.timestamp', function(timestamp) {
			$scope.timestampString = dateFilter(timestamp, "MM-dd-yyyy");
		});

		$scope.$watch('timestampString', function(timestampString) {

			if (angular.isDate(timestampString)) {
				$scope.newLog.timestamp = new Date(timestampString);
			} 
		});
		
		// /////////////////////////////////////////////
		/*
		$scope.saveLog = function() {

			delete $http.defaults.headers.common['X-Requested-With'];
			
			$scope.save(angular.toJson($scope.newLog));
		}
		*/
		// ////////////////////////////////////////////
		
		// PAGINATION 
		
	    // init
	    $scope.sort = {
	        sortingOrder: 'id',
	        reverse: false
	    };

	    $scope.gap = 5;
	    $scope.itemsPerPage = 5;
	    $scope.currentPage = 0;

	    $scope.filteredItems = [];
	    $scope.groupedItems = [];
	    $scope.pagedItems = [];
	    

	    var searchMatch = function(haystack, needle) {
	        if (!haystack || !needle) {
	            return true;
	        }
	        return haystack.toLowerCase().indexOf(needle.toLowerCase()) !== -1;
	    };

	    // init the filtered items
	    $scope.search = function() {
	        $scope.filteredItems = $filter('filter')($scope.logs, function(item) {
	            for (var attr in item) {
	                if (searchMatch(item[attr], $scope.query))
	                    return true;
	            }
	            return false;
	        });
	        // take care of the sorting order
	        if ($scope.sort.sortingOrder !== '') {
	            $scope.filteredItems = $filter('orderBy')($scope.filteredItems, $scope.sort.sortingOrder, $scope.sort.reverse);
	        }
	        $scope.currentPage = 0;
	        // now group by pages
	        $scope.groupToPages();
	    };


	    // calculate page in place
	    $scope.groupToPages = function() {
	        $scope.pagedItems = [];

	        for (var i = 0; i < $scope.filteredItems.length; i++) {
	            if (i % $scope.itemsPerPage === 0) {
	                $scope.pagedItems[Math.floor(i / $scope.itemsPerPage)] = [$scope.filteredItems[i]];
	            } else {
	                $scope.pagedItems[Math.floor(i / $scope.itemsPerPage)].push($scope.filteredItems[i]);
	            }
	        }
	    };

	    $scope.range = function(size, start, end) {
	        var ret = [];
	        console.log(size, start, end);

	        if (size < end) {
	            end = size;
	            start = size - $scope.gap;
	        }
	        for (var i = start; i < end; i++) {
	        	if (i >= 0) {
	        		ret.push(i);
	        	}
	            
	        }
	        console.log(ret);
	        return ret;
	    };

	    $scope.prevPage = function() {
	        if ($scope.currentPage > 0) {
	            $scope.currentPage--;
	        }
	    };

	    $scope.nextPage = function() {
	        if ($scope.currentPage < $scope.pagedItems.length - 1) {
	            $scope.currentPage++;
	        }
	    };

	    $scope.setPage = function() {
	        $scope.currentPage = this.n;
	    };

	    // functions have been describe process the data for display
//	    $scope.search();


		
	} ]);
	
	app.directive("customSort", function() {
	    return {
	        restrict: 'A',
	        transclude: true,
	        scope: {
	            order: '=',
	            sort: '='
	        },
	        template: ' <a ng-click="sort_by(order)" style="color: #555555;">' +
	            '    <span ng-transclude></span>' +
	            '    <i ng-class="selectedCls(order)"></i>' +
	            '</a>',
	        link: function(scope) {

	                // change sorting order
	                scope.sort_by = function(newSortingOrder) {
	                    var sort = scope.sort;

	                    if (sort.sortingOrder == newSortingOrder) {
	                        sort.reverse = !sort.reverse;
	                    }

	                    sort.sortingOrder = newSortingOrder;
	                };


	                scope.selectedCls = function(column) {
	                    if (column == scope.sort.sortingOrder) {
	                        return ('icon-chevron-' + ((scope.sort.reverse) ? 'down' : 'up'));
	                    } else {
	                        return 'icon-sort'
	                    }
	                };
	            } // end link
	    }
	});
	
	
})();